package com.commerce.reader.ui.dashboard;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import com.commerce.reader.Activity.DescActivity;
import com.commerce.reader.Entity.Books;
import com.commerce.reader.R;
import com.commerce.reader.adapter.MycardAdapter;

import java.io.Serializable;
import java.util.List;

public class DashboardFragment extends Fragment {

    private DashboardViewModel dashboardViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        dashboardViewModel =
                new ViewModelProvider(this).get(DashboardViewModel.class);
        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
        final GridView gridView = root.findViewById(R.id.fd_cv_card_book);
        final EditText editText = root.findViewById(R.id.fd_et_search);
        final Button button = root.findViewById(R.id.fd_btn_search);
        dashboardViewModel.getBooks().observe(getViewLifecycleOwner(), new Observer<List<Books>>() {
            @Override
            public void onChanged(List<Books> books) {
                MycardAdapter mycardAdapter = new MycardAdapter(getActivity(), books);
                gridView.setAdapter(mycardAdapter);
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dashboardViewModel.fBooks(editText.getText().toString());
            }
        });
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                LiveData<List<Books>> books = dashboardViewModel.getBooks();
                Intent intent = new Intent(getActivity(), DescActivity.class);
                intent.putExtra("books", (Serializable) books.getValue().get((int) l));
                startActivity(intent);
            }
        });
        return root;
    }
}